import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;


public class RegisterServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	String customerName ="";
	String customerPass = "";
	Document registerInf;
	String customerID ="";
	HttpSession session = null;
	Namespace ns = Namespace.getNamespace("http://www.cs.au.dk/dWebTek/2011");

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
	IOException {
		customerName = req.getParameter("username");
		customerPass = req.getParameter("password");
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		try {
			if (!allowUser(customerName, customerPass)) {
				out.println("<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD>");
				out.println("<BODY>Your username and password are invalid.<BR>");
				out.println("You may want to <A HREF=\"/MovieStore/\">try again</A>");
				out.println("</BODY></HTML>");
			} else {
				// Valid login. Make a note in the session object.
				session = req.getSession();
				session.setAttribute("loginInf", registerInf.getRootElement().getChild("customerID",ns));

				// Try redirecting the client to the page he first tried to access
				try {
					String target = "index.jsp";
					if (target != null) {
						res.sendRedirect(target);
						return;
					}
				} catch (Exception ignored) {
				}

				// Couldn't redirect to the target. Redirect to the site's home page.
				res.sendRedirect("/");
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}


	protected boolean allowUser(String account, String password) throws IOException, JDOMException {
		String urlText = "http://services.brics.dk/java/cloud/createCustomer";
		Namespace ns = Namespace.getNamespace("http://www.cs.au.dk/dWebTek/2011");

		//define xml tree
		Document xmlDoc = new Document();

		//add root element
		Element root = new Element("createCustomer");
		root.setNamespace(ns);
		xmlDoc.setRootElement(root);

		//add child element "shopKey"
		Element ele = new Element("shopKey", ns);
		ele.setText("8259472FBED5DE4AD1FB0839");
		root.addContent(ele);

		//add child element "customerName"
		ele = new Element("customerName", ns);
		ele.setText(customerName);
		root.addContent(ele);

		//add child element "customerPass"
		ele = new Element("customerPass", ns);
		ele.setText(customerPass);
		root.addContent(ele);


		try {
			HttpURLConnection c = (HttpURLConnection) new URL(urlText).openConnection();

			//outputter with prettyprint added
			XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());

			//output
			c.setDoOutput(true);
			OutputStreamWriter writer = new OutputStreamWriter(c.getOutputStream(), "UTF-8");
			outputter.output(xmlDoc, writer);
			writer.close();
			registerInf = new SAXBuilder().build(c.getInputStream());

			//outputter.output(loginInf, System.out);

		} catch (IOException e) {
			e.printStackTrace();
		}

		if(registerInf!=null){
			if(registerInf.getRootElement().getChild("usernameTaken", ns)==null){
				{
					return true;
				}
			}
		}
		return false;
	}
}
